import {getToken,setToken,removeToken} from "@/utils/auth";
import {message} from "ant-design-vue";
import {login} from '@/api/user'
import {nextTick} from "vue";
import router from "@/router";

interface loginForm {
    userName:string,
    userPassword:string,
}
// 做了持久化 下面的头像等 其实没有必有做了
const user = {
    namespaced:true,
    state:{
        token: getToken(),
        userAvatar:'',
        userType:'',
        userName:'',
        userInfo:{}
    },
    mutations:{
        SET_TOKEN(state:any,token:string){
            state.token = token;
            setToken(token)
        },
        SET_USER_AVATAR(state:any,userAvatar:string){
            state.userAvatar = userAvatar
        },
        SET_USER_TYPE(state:any,userType:string){
            state.userType = userType
        },
        SET_USER_NAME(state:any,userName:string){
            state.userName = userName
        },
        SET_USER_INFO(state:any,userInfo:any){
            state.userInfo = userInfo
        },
        LOGOUT(state:any){
            nextTick(() => {
                removeToken()
                localStorage.removeItem('blog-admin')
                router.push('/login')
            })
        }
    },
    actions:{
        async login(ctx:any,loginForm:loginForm){
            const res:any = await login(loginForm);
            let {userName,userAvatart,userType} = res.userInfo
            ctx.commit('SET_TOKEN',res.token)
            ctx.commit('SET_USER_INFO',res.userInfo)
            ctx.commit('SET_USER_NAME',userName)
            ctx.commit('SET_USER_AVATAR',userAvatart)
            ctx.commit('SET_USER_TYPE',userType)
        }
    }
}

export default user
